package com.atguigu.redis7.canel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry.*;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


//双写一致性
//先更新mysql  再操作redis
@Component
public class RedisCanalClientExample {
    public static final Integer _60SECONDS = 60;
    public static final String REDIS_IP_ADDR = "192.168.190.132";
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    public RedisTemplate redisTemplate;

    private void redisInsert(List<Column> columns) {

        JSONObject jsonObject = new JSONObject();
        for (Column column : columns) {
            System.out.println(column.getName() + " : " + column.getValue() + "    update=" + column.getUpdated());
            jsonObject.put(column.getName(), column.getValue());
        }
        if (columns.size() > 0) {
            try {
                redisTemplate.opsForValue().set(columns.get(0).getValue(), jsonObject.toJSONString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private void redisDelete(List<Column> columns) {
        JSONObject jsonObject = new JSONObject();
        for (Column column : columns) {
            jsonObject.put(column.getName(), column.getValue());
        }
        if (columns.size() > 0) {
            try {
                redisTemplate.delete(columns.get(0).getValue());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void redisUpdate(List<Column> columns) {
        JSONObject jsonObject = new JSONObject();
        for (Column column : columns) {
            System.out.println(column.getName() + " : " + column.getValue() + "    update=" + column.getUpdated());
            jsonObject.put(column.getName(), column.getValue());
        }
        if (columns.size() > 0) {
            try {
                int a = 1 / 0;  //模拟异常
                //mysql更新  redis删除
                redisTemplate.delete(columns.get(0).getValue());
            } catch (Exception e) {

                //这里删除失败的话，需要发送信息给消息队列

                //1、消息配置
                MessageProperties messageProperties = new MessageProperties();
                messageProperties.setAppId(UUID.randomUUID().toString());
                messageProperties.setContentType("application/text");
                messageProperties.setContentEncoding("UTF-8");


                String msg = columns.get(0).getValue();

                //2、消息
                Message message = new Message(JSON.toJSONBytes(msg), messageProperties);


                //5、发送数据
                rabbitTemplate.convertAndSend("userExchange", "user.update", msg);

                System.out.println("发送信息给rabbitmq");
            }
        }
    }

    public void printEntry(List<Entry> entrys) {
        for (Entry entry : entrys) {
            //事务开始或者结束不处理
            if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND) {
                continue;
            }

            RowChange rowChage = null;
            try {
                //获取变更的row数据
                rowChage = RowChange.parseFrom(entry.getStoreValue());
            } catch (Exception e) {
                throw new RuntimeException("ERROR ## parser of eromanga-event has an error,data:" + entry.toString(), e);
            }
            //获取变动类型
            EventType eventType = rowChage.getEventType();
            System.out.println(String.format("================&gt; binlog[%s:%s] , name[%s,%s] , eventType : %s",
                    entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
                    entry.getHeader().getSchemaName(), entry.getHeader().getTableName(), eventType));

            for (RowData rowData : rowChage.getRowDatasList()) {
                //添加
                if (eventType == EventType.INSERT) {
                    redisInsert(rowData.getAfterColumnsList());
                }
                //删除
                else if (eventType == EventType.DELETE) {
                    redisDelete(rowData.getBeforeColumnsList());
                }
                //更新
                else {//EventType.UPDATE
                    redisUpdate(rowData.getAfterColumnsList());
                }
            }
        }
    }


//    @PostConstruct
    public void test() {

        //=================================
        // 创建链接canal服务端
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(REDIS_IP_ADDR,
                11111), "example", "", "");
        int batchSize = 1000;
        //空闲空转计数器
        int emptyCount = 0;
        System.out.println("---------------------canal init OK，开始监听mysql变化------");
        try {
            connector.connect();
            //connector.subscribe(".*\\..*");
            connector.subscribe("db.user"); //配置过滤规则
            connector.rollback();
            int totalEmptyCount = 10 * _60SECONDS; //10分钟
            //任意10分钟内无信息，则退出，不会一直跑
            while (emptyCount < totalEmptyCount) {
//                System.out.println("我是canal，每秒一次正在监听:" + UUID.randomUUID().toString());
                com.alibaba.otter.canal.protocol.Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据
                long batchId = message.getId();
                int size = message.getEntries().size();
                if (batchId == -1 || size == 0) {
                    emptyCount++;
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    //计数器重新置零
                    emptyCount = 0;
                    printEntry(message.getEntries());
                }
                connector.ack(batchId); // 提交确认
                // connector.rollback(batchId); // 处理失败, 回滚数据
            }
            System.out.println("已经监听了" + totalEmptyCount + "秒，无任何消息，请重启重试......");
        } finally {
            connector.disconnect();
        }
    }


}